<template>
  <div class="full-box d-flex bg-white">
    <BKTabs
      tab-position="left"
      v-model="currentTab"
      :data="tabs"
    />
    <div
      class="flex-1 overflow-hidden d-flex bg-white"
      v-if="tabLoaded"
    >
      <BKMutableContainer
        left-width="300"
        max-left-width="300"
        min-left-width="300"
      >
        <template #left>
          <ConfigTree
            :configs="configs"
            :tree-query-params="treeQueryParams"
            ref="tree"
            @menuClick="menuClick"
            @nodeClicked="nodeClicked"
            @dataLoaded="getPollingData"
          />
        </template>
        <div
          class="full-box iframe-wapper"
          v-if="show && showType === 'url' && src"
          v-loading="loading"
        >
          <iframe
            :src="src"
            style="border: none;"
            ref="iframe"
            :class="['full-box', iframeClass]"
          />
        </div>
        <ImgContainer
          v-if="show && showType === 'img'"
          class="full-box"
          :src="src"
        />
        <component
          :is="component"
          v-if="show && showType === 'component' && component"
        />
        <el-empty
          v-else
          class="full-box"
          description="请选择文件"
        />
      </BKMutableContainer>
      <ConfigForm
        :configs="formConfigs"
        ref="form"
        :before-submit="beforeSubmit"
        @saveSuccess="saveSuccess"
        @finishLoading="finishLoading"
      />
    </div>
  </div>
</template>

<script>
import ImgContainer from '@/components/img-container'
import { external } from '@/utils/request'
import { mapState } from 'vuex'

const fileType = {
  1: 'img',
  2: 'component',
  3: 'url'
}
export default {
  name: 'Report',
  components: {
    ImgContainer
  },
  data () {
    return {
      tabs: [],
      currentTab: '',
      configs: {
        appId: 'YSJC',
        bzCode: 'YSJC',
        treeConfigId: 'REPORT_TREE',
        renderContent: this.renderContent,
        menuConfig: [
          { title: '新增下级文件夹或文件', visible: (data) => data.att6 === '2', key: 'addFolder' },
          { title: '编辑', visible: (data) => true, key: 'editFolder' },
          { title: '删除', visible: (data) => true, key: 'removeFolder' }
        ],
        management: {
          metaSet: 'YSQJC_REPORT_SYSTEM_TABLE',
          module: '',
          modal: {
            width: 500
          }
        },
        customAddTopTreeNode: this.customAddTopTreeNode,
        canSortItem: true,
        sortKeyProps: {
          id: 'MENU_ID',
          fid: 'PARENT_ID',
          order: 'ORDER_NUM'
        },
        onDraggableMove: this.onDraggableMove,
        checkFolderMethod: this.checkFolderMethod
      },
      tabLoaded: false,
      show: false,
      showType: 'url',
      src: '',
      loading: false,
      component: null,
      currentFileType: '2',
      pollingCheckData: {},
      iframeClass: '',
      emptyText: ''
    }
  },
  computed: {
    ...mapState('user', ['token']),
    treeQueryParams () {
      return {
        bzCode: 'YSJC',
        id: this.currentTab
      }
    },
    formConfigs () {
      return {
        appId: this.configs.appId,
        bzCode: this.configs.bzCode,
        ...this.configs.management,
        primaryKeyProps: {
          MENU_ID: 'id'
        },
        formItemProcessor: this.formItemProcessor,
        formSubmitUrl: this.currentFileType === '1' ? '/ysjc/ztt/uploadReportPDF' : '/SingleTable/curd'
      }
    }
  },
  created () {
    this.initTabs()
    this.requireComponent = require.context('./templates/', true, /\.vue$/)
  },
  watch: {
    currentTab (v) {
      if (this.tabLoaded) {
        this.$nextTick(() => {
          this.$refs.tree.refreshAllNodes()
        })
      }
    }
  },
  methods: {
    async initTabs () {
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: 'YSQJC_REPORT_SYSTEM',
        methodCode: 'select',
        mehtodParams: {}
      })
      this.tabs = rows.map(item => ({ name: item.ID, label: item.SYSTEM_NAME }))
      this.currentTab = rows[0].ID
      this.tabLoaded = true
    },
    renderContent (h, { node, data, store }) {
      return (
        <div class="custom-tree-node d-flex ai-c">
          {
            <span class="p-l-s node-icon f-14">
              {
                data.att6 === '2' ? <i class="icon ri-folder-line c-grey"/> : null
              }
              {
                data.att6 !== '2'
                  ? <i class={`icon ${this.pollingCheckData[data.id] === false ? 'el-icon-loading' : 'ri-file-line'} c-grey`} style={{ top: this.pollingCheckData[data.id] === false ? '8%' : '50%' }}/>
                  : null
              }
              <span>{ node.label }</span>
            </span>
          }
        </div>
      )
    },
    menuClick (menu, data) {
      this[menu.key](data)
    },
    customAddTopTreeNode () {
      this.isEdit = false
      this.$refs.form.show({ IS_FILE: '2', PARENT_ID: 'ROOT', ID: this.currentTab, ORDER_NUM: (this.treeData[this.treeData.length - 1]?.treeOrder || 0) + 1 }, false)
    },
    addFolder (node) {
      this.isEdit = false
      this.$refs.form.show({ IS_FILE: '2', PARENT_ID: node.id, ID: this.currentTab, ORDER_NUM: (node.children[node.children.length - 1]?.treeOrder || 0) + 1 }, false)
    },
    async editFolder (node) {
      this.isEdit = true
      this.$refs.form.show(node, true)
    },
    removeFolder (node) {
      console.log(node)
      const value = this.recurseHandleHasFile(node)
      if (!value) {
        this.$confirm('请确认是否删除该文件夹', '提示', { type: 'warning' }).then(async () => {
          await this.$request.singleTableOperation({
            metaSet: this.formConfigs.metaSet,
            methodCode: 'delete',
            methodParams: {
              MENU_ID: node.id
            }
          })
          this.$message.success('删除成功')
          this.$refs.tree.refreshAllNodes()
        })
      } else {
        this.$message.warning('请先删除此文件夹下的文件再进行删除操作')
      }
    },
    beforeSubmit (form) {
      if (this.currentFileType === '1' && !form.MENU_ID) {
        return { JBXX: form }
      } else {
        return {
          appId: this.formConfigs.appId,
          bzCode: this.formConfigs.bzCode,
          metaSet: this.formConfigs.metaSet,
          methodCode: this.isEdit ? 'update' : 'insert',
          methodParams: JSON.stringify(form)
        }
      }
    },
    recurseHandleHasFile (node) {
      if (node.children && node.children.length) {
        for (const item of node.children) {
          if (item.att6 === '1') {
            return true
          } else {
            return this.recurseHandleHasFile(item)
          }
        }
      }
      return false
    },
    async saveSuccess (t, { form, resData }) {
      if (form.JBXX) {
        const formData = form.JBXX
        if (formData.IS_FILE === '1' && resData && formData.UPLOADWJLJ) {
          this.startPollingCheck(resData)
        }
      }
      this.$refs.tree.refreshAllNodes()
    },
    checkFolderMethod (item) {
      return item.att6 === '2'
    },
    onDraggableMove (data) {
      return true
      // if (data.draggedContext.element?.fid === data.relatedContext.element?.fid) {
      //   return true
      // }
      // if (data.draggedContext.element.att6 === '1') {
      //   // 拖拽菜单
      //   if (data.relatedContext.element) {
      //     // 改变顺序
      //     return data.relatedContext.element.att6 === '1'
      //   } else {
      //     return true
      //   }
      // } else {
      //   // 拖拽目录
      //   if (data.relatedContext.element) {
      //     return data.relatedContext.element.att6 === '2'
      //   } else {
      //     return true
      //   }
      // }
    },
    async nodeClicked (data) {
      console.log(data)
      this.loading = false
      if (this.currentNode && this.currentNode.id === data.id) return
      this.currentNode = data
      if (data.att6 === '1' || data.att6 === '3') {
        this.showType = fileType[data.att9]
        if (this.showType === 'url' && data.att7) {
          this.iframeClass = data.att10
          // 登录
          if (data.att7.startsWith(window.outApiHw1)) {
            const res = await external.post(window.outApiHw1 + 'hw-api/auth/login', {
              account: 'rYEoOoQcNT4bFp7ljNxOFg==',
              password: 'bKd/3mp9AH4fLXCmOKm3Lw==',
              uuid: ''
            })
            const token = res.data.data
            if (token) {
              this.src = data.att7 + '?accessToken=' + token + '&isIframe=1'
            }
          } else if (data.att7.startsWith(window.outApiBase)) {
            this.src = data.att7 + '?ticket=' + this.token
          } else if (data.att7.startsWith(window.outApiReceiveFront)) {
            const res = await external.get(window.outApiReceiveBackend + '/swpm-admin/swpm/hwapp/login?userName=swcjcyb')
            this.src = data.att7 + '?accessToken=' + res.data.data + '&isIframe=1'
          } else {
            this.src = data.att7
          }
        } else {
          this.src = data.att7
        }
        this.show = true
        if (this.showType === 'url' && this.src) {
          this.loading = true
          this.$nextTick(() => {
            this.$refs.iframe.onload = () => {
              this.loading = false
            }
          })
        } else if (this.showType === 'component') {
          try {
            const componentConfig = this.requireComponent('./' + data.att7 + '.vue')
            this.component = componentConfig.default
          } catch (error) {
            console.log(error)
            this.component = null
          }
        }
      } else {
        this.show = false
        this.emptyText = '请选择文件'
      }
    },
    formItemProcessor ({ items, rules }) {
      for (const item of items) {
        if (item.field === 'IS_FILE') {
        // 临时代码
          item.props.mock = [
            { label: '文件', value: '1' },
            { label: '文件夹', value: '2' },
            { label: '地址', value: '3' }
          ]
          item.events = {
            change: this.changeType
          }
        }
      }
      items.push({
        label: '链接',
        field: 'FILE_PATH',
        type: 'input'
      })
      return { items, rules }
    },
    changeType (value) {
      if (value === '1') {
        this.$refs.form.$refs.form.setItemVisible({ UPLOADWJLJ: true })
        this.$refs.form.$refs.form.setItemVisible({ FILE_PATH: false })
        const { FILE_LX } = this.$refs.form.$refs.form.getFormData()
        if (!FILE_LX) {
          this.$refs.form.$refs.form.setFormData({ FILE_LX: '3' })
        }
      } else if (value === '2') {
        this.$refs.form.$refs.form.setItemVisible({ UPLOADWJLJ: false })
        this.$refs.form.$refs.form.setItemVisible({ FILE_PATH: false })
      } else if (value === '3') {
        this.$refs.form.$refs.form.setItemVisible({ UPLOADWJLJ: false })
        this.$refs.form.$refs.form.setItemVisible({ FILE_PATH: true })
        const { FILE_LX } = this.$refs.form.$refs.form.getFormData()
        if (!FILE_LX) {
          this.$refs.form.$refs.form.setFormData({ FILE_LX: '3' })
        }
      }
      this.currentFileType = value
    },
    finishLoading (form) {
      const formData = form.getFormData()
      this.remoteUploadFilePath = formData.UPLOADWJLJ
      this.changeType(formData.IS_FILE)
    },
    async startPollingCheck (id) {
      if (this.stamp) {
        clearInterval(this.stamp)
      }
      this.stamp = setInterval(async () => {
        const data = await this.$request.post('/ysjc/ztt/getCacheJD', {})
        let needRefresh = false
        if (!data.length) {
          this.pollingCheckData = {}
          clearInterval(this.stamp)
          this.stamp = null
          needRefresh = true
        } else {
          for (const MENU_ID in this.pollingCheckData) {
            if (Object.hasOwnProperty.call(this.pollingCheckData, MENU_ID)) {
              if (!data.includes(MENU_ID)) {
                delete this.pollingCheckData[MENU_ID]
                needRefresh = true
              }
            }
          }
        }
        needRefresh && this.$refs.tree.refreshAllNodes()
      }, 5000)
    },
    async getPollingData (data) {
      console.log(data)
      this.treeData = data
      const res = await this.$request.post('/ysjc/ztt/getCacheJD', {})
      if (res && res.length) {
        const obj = {}
        res.forEach(item => {
          obj[item] = false
        })
        this.pollingCheckData = obj
        this.startPollingCheck()
      } else {
        this.pollingCheckData = {}
      }
    }
  },
  activated () {
    if (!this.nofirstLoad) {
      this.getPollingData()
    } else {
      this.nofirstLoad = true
    }
  },
  deactivated () {
    if (this.stamp) {
      clearInterval(this.stamp)
      this.stamp = null
    }
  }
}
</script>
